package com.fintech.third.service;

import com.fintech.common.util.PropertiesUtils;
import com.fintech.third.constant.LocalStatus;
import com.fintech.third.constant.ThirdProductChannelConstant;
import com.fintech.third.constant.ThirdProductConstant;
import com.fintech.third.dao.MessageIndustryMapper;
import com.fintech.third.dao.SmsMapper;
import com.fintech.third.dao.SmsTemplateMapper;
import com.fintech.third.dao.ThirdProductChannelMappper;
import com.fintech.third.model.ThirdProductChannel;
import com.fintech.third.model.ThirdProperties;
import com.fintech.third.model.message.*;
import com.fintech.third.utils.ApplicationContextGet;
import com.fintech.third.utils.ThirdPropertiesInitUtil;
import com.marvels.common.utils.MarvelsLogUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 短信发送失败或成功处理
 * @author tangpw
 *
 */
@Component("smsDataDeal")
public class SmsDataDeal {

	@Resource(name="smsMapper")
	private SmsMapper smsMapper;
	@Autowired
	private MessageIndustryMapper messageIndustryMapper;
	
	@Autowired
	private SmsTemplateMapper smsTemplateMapper;
	
	/**
	 * 查询该类型短信当天发送了多少次
	 * @param phone
	 * @param templateId
	 * @return
	 */
	public Integer querySendSuccussCount(String phone, String templateId){
		Integer number = 0;
		try {
			number = smsMapper.querySendSuccussCount(phone, templateId);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("查询手机号:" + phone + "模板id：" + templateId + "当日发送次数异常", e);
		}
		return number;
	}
	/**
	 * 处理发送成功短信信息
	 */
	public void dealSmsSendInfo(String createTime,String templateId,String src,String templateContent,String phone,String detailId,String bitchNo,String msgBathId,String messageCategory,String channelCode){
		SmsSend send = new SmsSend();
		send.setCreate_time(createTime);
		send.setTemplate_id(Long.parseLong(templateId));
		send.setSrc(src);
		send.setMsg(templateContent);
		send.setPhone(phone);
		send.setBatch_no(bitchNo);
		send.setSend_status("1");
		send.setDetail_id(detailId);
		send.setMsg_bathId(msgBathId);
		send.setMessage_category(messageCategory);
		send.setChannel_code(channelCode);
		try {
			smsMapper.insertSmsSend(send);
		} catch (Exception e) {
			e.printStackTrace();
			MarvelsLogUtil.getInstance().info("============>>>已发送短信入库异常:" + e.getMessage());
		}
	}
	
	
	/**
	 * 处理发送成失败短信信息
	 */
	public void dealSmsSendFailure(String createTime,String templateId,String src,String templateContent,String phone,String detailId,String bitchNo,String msgBathId,String messageCategory,String channelCode,String remark){
		SmsSendFailure sendFailure = new SmsSendFailure();
		sendFailure.setCreate_time(createTime);
		sendFailure.setTemplate_id(Long.parseLong(templateId));
		sendFailure.setSrc(src);
		sendFailure.setMsg(templateContent);
		sendFailure.setPhone(phone);
		sendFailure.setDetail_id(detailId);
		sendFailure.setBatch_no(bitchNo);
		sendFailure.setMsg_bathId(msgBathId);
		sendFailure.setMessage_category(messageCategory);
		sendFailure.setChannel_code(channelCode);
		sendFailure.setRemark(remark);
		try {
			smsMapper.insertSmsSendFailure(sendFailure);
		} catch (Exception e) {
			e.printStackTrace();
			MarvelsLogUtil.getInstance().info("============>>>发送失败短信入库异常:" + e.getMessage());
		}
	}
	
	
	
	public boolean smsDealAndSend(String createTime, String templateId, String src, String templateContent,
			String phone, String detailId, String bitchNo,String messageCategory,String channelCodeChoose) {
		/*
		 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
		 */
		if (PropertiesUtils.isTurnOffForSwitch("switch.sms001")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			return false;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		Date startDate = new Date();
		String thirdMethodConstants = null; // 接口名
		boolean bool = true;
		ThirdProductChannelMappper thirdProductChannelMappper = (ThirdProductChannelMappper) ApplicationContextGet
				.getApplicationContext().getBean("thirdProductChannelMappper");
		ResponseData responseData = null;
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		String  channelCode="";
		SmsTemplate smsTemplate=smsTemplateMapper.obtainSmsTemplateContent(Long.parseLong(templateId));
		if(smsTemplate!=null && StringUtils.isNotBlank(smsTemplate.getChannel_code())){//判断是平台短信  设定了走那个短信通道
			channelCode=smsTemplate.getChannel_code();
		}else if(smsTemplate!=null && StringUtils.isBlank(smsTemplate.getChannel_code())){//判断是平台短信  没有走那个短信通道则走默认的优先级的短信通道
			ThirdProductChannel productChannelDto = thirdProductChannelMappper.queryAvailableChannel(ThirdProductConstant.SMS.getCode());
			channelCode=productChannelDto.getCode();
		}else if(smsTemplate==null && StringUtils.isNotBlank(channelCodeChoose)){//判断是核心后台的短信
			channelCode=channelCodeChoose;
		}
		MessageIndustryDto messageIndustryDto=messageIndustryMapper.selectMessageIndustryMapper(ThirdProductConstant.SMS.getCode(),channelCode,templateId);
		if (Boolean.parseBoolean(thirdProperties.getIs_sms_send())) {// 发送短信
			try {
				if (ThirdProductChannelConstant.TRUETESTSMS.getCode().equals(channelCode)) {// 中正云通讯短信
					String string = SmsChannelSend.middleClubSms(phone, templateContent);
					String[] strings = string.split("/");
					if ("000".equals(strings[0])) {
						dealSmsSendInfo(createTime, templateId, src, templateContent, phone, detailId, bitchNo, "",messageCategory,channelCode);

						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						dealSmsSendFailure(createTime, templateId, src, templateContent, phone, detailId, bitchNo, "",messageCategory,channelCode, "");
						bool = false;
						
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = strings[0];
					thirdMethodConstants = ThirdProductChannelConstant.TRUETESTSMS.getCode();
				} else if (ThirdProductChannelConstant.TENCENTSMS.getCode().equals(channelCode)) {// 腾讯云短信
					responseData = SmsChannelSend.tencentSms(phone, templateContent);
					MarvelsLogUtil.getInstance().info("send_note_error===>>" + responseData.getError());
					JSONObject result_json = JSONObject.fromObject(responseData.getBody());
					if ("0".equals(result_json.get("result"))) {
						dealSmsSendInfo(createTime, templateId, src, templateContent, phone, detailId, bitchNo, "",messageCategory,channelCode);

						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						dealSmsSendFailure(createTime, templateId, src, templateContent, phone, detailId, bitchNo, "",messageCategory,channelCode, "");
						bool = false;
						
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = result_json.get("result") + "";
					thirdMethodConstants = ThirdProductChannelConstant.TENCENTSMS.getCode();

				} else if ( ThirdProductChannelConstant.MICRONETCOMSMS.getCode().equals(channelCode)) {// 微网通联短信
					if((messageIndustryDto!=null && messageIndustryDto.getIndustry().equals("2")) || messageCategory.equals("2")){//营销
						messageCategory="2";
					}else if((messageIndustryDto!=null && messageIndustryDto.getIndustry().equals("3")) || messageCategory.equals("3")){//行业通知
						messageCategory="3";
					}else {//行业触发
						messageCategory="1";
					}
					MicroNetResponse microNetResponse = SmsChannelSend.microNetcomSms(phone, templateContent,messageCategory);
					if ("0".equals(microNetResponse.getState())) {
						dealSmsSendInfo(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
								microNetResponse.getMsgID(),messageCategory,channelCode);

						status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					} else {
						dealSmsSendFailure(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
								microNetResponse.getMsgID(),messageCategory,channelCode, "");
						
						status = LocalStatus.REQUEST_FAIL.getCode();
					}
					thirdCode = microNetResponse.getState();
					thirdMethodConstants = ThirdProductChannelConstant.MICRONETCOMSMS.getCode();
				} else if ( ThirdProductChannelConstant.SPEEDSHIELD.getCode().equals(channelCode)) {// 速盾短信
					Map<String, String> map = new HashMap<String, String>();
					map.put("mobile", phone);
					map.put("msg", templateContent);
					String result="";
					if((messageIndustryDto!=null && messageIndustryDto.getIndustry().equals("2")) || messageCategory.equals("2")){
						map.put("content", templateContent);
						result = SmsChannelSend.SpeedShieldTechnologyCollection(map);
					}else{
						result = SmsChannelSend.SpeedShieldTechnology(map);
					}
					String msgId = "";
					if(StringUtils.isNotEmpty(result)){
						String[] strings=new String[1];
						strings=result.split(",");
						String[] string=strings[1].split("\n");
						if(string[0].equals("0")){//成功
							msgId=string[1];
							dealSmsSendInfo(createTime, templateId, src, templateContent, phone, detailId, bitchNo, msgId,messageCategory,channelCode);

							status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
						}else{
							dealSmsSendFailure(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
									msgId,messageCategory,channelCode, "");
							bool = false;
							
							status = LocalStatus.REQUEST_FAIL.getCode();
						}
						thirdCode = string[0];
					}else{
						bool = false;
						status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
					}
					thirdMethodConstants = ThirdProductChannelConstant.SPEEDSHIELD.getCode();
				}else if (ThirdProductChannelConstant.CHUANGLAN.getCode().equals(channelCode)) {// 创蓝短信
					MarvelsLogUtil.getInstance().info("===============调用创蓝短信方法,手机号:"+phone);
					Map<String, String> map = new HashMap<String, String>();
					map.put("mobile", phone);
					map.put("msg", templateContent);
					if((messageIndustryDto!=null && messageIndustryDto.getIndustry().equals("2")) || messageCategory.equals("2")){//会员营销短信
						messageCategory="2";
					}else{//验证码通知短信
						messageCategory="1";
					}
					map.put("messageCategory", messageCategory);
					String result=SmsChannelSend.createBuleMsg(map);
					String msgId = "";
					if(StringUtils.isNotEmpty(result)){
						if(StringUtils.isNotEmpty(result)){
							JSONObject jsonResult=JSONObject.fromObject(result);
							if(jsonResult.get("code").equals("0")){//
								msgId=jsonResult.getString("msgId");
								dealSmsSendInfo(createTime, templateId, src, templateContent, phone, detailId, bitchNo, msgId,messageCategory,channelCode);

								status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
							}else{
								dealSmsSendFailure(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
										msgId,messageCategory,channelCode, "");
								bool = false;
								
								status = LocalStatus.REQUEST_FAIL.getCode();
							}
							thirdCode = jsonResult.get("code") + "";
						}
					}else{
						bool = false;
						status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
					}
					thirdMethodConstants = ThirdProductChannelConstant.CHUANGLAN.getCode();
				} else if (ThirdProductChannelConstant.MENGWANG.getCode().equals(channelCode)) {// 梦网短信
					MarvelsLogUtil.getInstance().info("===============调用梦网短信方法,手机号:" + phone);
					Map<String, String> map = new HashMap<String, String>();
					map.put("mobile", phone);
					map.put("msg", templateContent);
					if ((messageIndustryDto != null && messageIndustryDto.getIndustry().equals("2")) || messageCategory.equals("2")) {// 会员营销短信
						messageCategory = "2";
					} else {// 验证码通知短信
						messageCategory = "1";
					}
					map.put("messageCategory", messageCategory);
					String result = SmsChannelSend.monternetMsg(map);
					String msgId = "";
					if (StringUtils.isNotEmpty(result)) {
						JSONObject jsonResult = JSONObject.fromObject(result);
						if (jsonResult.getInt("result") == 0) {// 成功
							msgId = jsonResult.getString("msgid");
							dealSmsSendInfo(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
									msgId, messageCategory,channelCode);

							status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
						} else {
							dealSmsSendFailure(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
									msgId, messageCategory,channelCode, "");
							bool = false;
							
							status = LocalStatus.REQUEST_FAIL.getCode();
						}
						thirdCode = jsonResult.get("code") + "";
					} else {
						bool = false;
						status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
					}
					thirdMethodConstants = ThirdProductChannelConstant.MENGWANG.getCode();
				}else if (ThirdProductChannelConstant.FENGHUODX.getCode().equals(channelCode)) {// 烽火短信
						MarvelsLogUtil.getInstance().info("===============调用烽火短信方法,手机号:" + phone);
						Map<String, String> map = new HashMap<String, String>();
						map.put("mobile", phone);
						map.put("msg", templateContent);
						if ((messageIndustryDto != null && messageIndustryDto.getIndustry().equals("2")) || messageCategory.equals("2")) {// 会员营销短信
							messageCategory = "2";
						} else {// 验证码通知短信
							messageCategory = "1";
						}
						map.put("messageCategory", messageCategory);
						String result = SmsChannelSend.fengHuoMsg(map);
						String msgId = "";
						if (StringUtils.isNotEmpty(result)) {
							String[] strings=result.split(":");
							if (strings[0].equals("success")) {// 成功
								msgId = strings[1];
								dealSmsSendInfo(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
										msgId, messageCategory,channelCode);

								status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
							} else {
								dealSmsSendFailure(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
										msgId, messageCategory,channelCode, "");
								bool = false;
								
								status = LocalStatus.REQUEST_FAIL.getCode();
							}
							thirdCode = strings[0];
						} else {
							bool = false;
							status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
						}
						thirdMethodConstants = ThirdProductChannelConstant.FENGHUODX.getCode();
					}else if (ThirdProductChannelConstant.EnterpriseMsg.getCode().equals(channelCode)) {// 烽火短信
						MarvelsLogUtil.getInstance().info("==============企业短信通接口,手机号:" + phone);
						Map<String, String> map = new HashMap<String, String>();
						map.put("mobile", phone);
						map.put("msg", templateContent);
						if ((messageIndustryDto != null && messageIndustryDto.getIndustry().equals("2")) || messageCategory.equals("2")) {// 会员营销短信
							messageCategory = "2";
						} else {// 验证码通知短信
							messageCategory = "1";
						}
						map.put("messageCategory", messageCategory);
						EnterpriseResponse enterpriseResponse = SmsChannelSend.EnterpriseMsg(map);
						String msgId = "";
						if (enterpriseResponse!=null && enterpriseResponse.getReturnstatus().equalsIgnoreCase("Success")) {
							msgId = enterpriseResponse.getTaskID();
							dealSmsSendInfo(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
									msgId, messageCategory,channelCode);

							status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
						} else {
							dealSmsSendFailure(createTime, templateId, src, templateContent, phone, detailId, bitchNo,
									msgId, messageCategory,channelCode, "");
							bool = false;
							
							status = LocalStatus.REQUEST_FAIL.getCode();
						}
						thirdCode = enterpriseResponse.getReturnstatus();
						thirdMethodConstants = ThirdProductChannelConstant.EnterpriseMsg.getCode();
					}
			} catch (Exception e) {
				e.printStackTrace();
				MarvelsLogUtil.getInstance().info("=========>>>>短信发送失败,短信内容:" + templateContent);
				dealSmsSendFailure(createTime, templateId, src, templateContent, phone, detailId, bitchNo, "",messageCategory,channelCode, "");

				return false;
			}
		} else {// 不发送短息
			dealSmsSendInfo(createTime, templateId, src, templateContent, phone, detailId, bitchNo, "",messageCategory,channelCode);
			return true;
		}

		return bool;
	}
}
